import sys
import os
import re
import amara
from brightcontent.core.store import COMMON_PREFIXES, ATOM10_NS
from brightcontent.util import fixup_namespaces
from amara.binderytools import quick_xml_scan

from optparse import OptionParser
import httplib2

def id_to_slug(id_):
    return re.sub('\W', '_', id_)
    #return '-'.join(id_.split('/')[-4:])
    #return id.replace(os.path.sep, '-')

def post_entry(h, url, entry, slug):
    headers = {'Content-type' : 'application/atom+xml', 'slug' : slug }
    resp, content = h.request(url, "POST", body=entry, headers=headers)
    return (resp, content)

def put_entry(h, url, entry):
    headers = {'Content-type' : 'application/atom+xml'}
    resp, content = h.request(url, "PUT", body=entry, headers=headers)
    return (resp, content)


if __name__ == '__main__':
    print >> sys.stderr, "NOTICE: Please place this script in the same location as your config file."
    parser = OptionParser()
    parser.add_option('-f', '--feed', dest='feedfile')
    parser.add_option('-u', '--url', dest='url')
    parser.add_option('-s', '--store-directory', dest='storedir')
    (options, args) = parser.parse_args()

    if not options.feedfile:
        parser.error('need a feed to import')
    input_file_or_url = options.feedfile
    
    if not options.storedir:
        parser.error('need a store directory to save a feed template')
    output_dir = options.storedir
    if not os.path.isdir(output_dir):
        os.mkdir(output_dir)

    if not options.url:
        parser.error('need a URL to POST to. Try http://localhost:8080/atom')
    posturl = '%s/%s' % (options.url.strip('/'), output_dir)

    doc = amara.parse(input_file_or_url, prefixes=COMMON_PREFIXES)
    envelope = amara.create_document(u"atom:feed", ns=ATOM10_NS)
    for nonentry in doc.feed.xml_xpath(u'*[not(self::atom:entry)]'):
        envelope.feed.xml_append(nonentry)

    f = open(os.path.join(output_dir, 'envelope.xml'), 'w')
    fixup_namespaces(envelope)
    f.write(envelope.xml(indent=u"yes"))
    f.close()

    h = httplib2.Http('.cache')
    for entry in doc.feed.entry:
        slug = id_to_slug(str(entry.title))
        print "Trying: post_entry(%s, %s, xml, %s)" % (h, posturl, slug)
        resp, content = post_entry(h, posturl, str(entry.xml()), slug)
        if resp['status'][0] != '2':
            print >> sys.stderr, 'Unexpected status', resp['status']
            break
        print "Created: %s" % resp['location']
        for k, v in resp.items():
            print '%s: %s' % (k, v)
        print content
    
    
